package server;

import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;

import common.Log;
import communication.Message;
import communication.MessageType;
import communication.message.GameId;
import communication.message.Player;
import communication.message.Result;
import communication.server.ClientHandle;
import communication.server.GMHandle;
import exception.ParseException;

public class ClientService implements Runnable{
	
	private ClientHandle clientHandle;
	private GMHandle gmHandle;
	private Socket socket;
	private volatile int winner = -1; //-1 niezdefiniowane, 0 przegrana, 1 winner
	
	public ClientService(ClientHandle clientHandle, GMHandle gmHandle, Socket socket) {
		this.clientHandle=clientHandle;
		this.socket=socket;
		this.gmHandle = gmHandle;
	}
	
	public int getWinner() {
		return winner; //-1 niezdefiniowane, 0 przegrana, 1 winner
	}
	
	public String getNick() {
		return clientHandle.getNick();
	}
	
	public void sendChampionList(ArrayList<Player> players) throws IOException {
		clientHandle.sendChampionList(players);
	}
	
	public ClientHandle getClientHandle() {
		return clientHandle;
	}
	
	public void setClientHandle(ClientHandle clientHandle) {
		this.clientHandle = clientHandle;
	}
	
	@Override
	public void run() {
		boolean work=true;
		while(work) {
			try {
				Message msg = clientHandle.receiveMessage();
				switch(msg.getType()) {
					case MOVE:						
						gmHandle.sendMessage(msg);
						break;
					case LEAVE_GAME:
						Message responseMsg = new Message(MessageType.PLAYER_LEFT_GAME);
						responseMsg.setGameId(msg.getGameId());
						responseMsg.setPlayer(new Player(clientHandle.getNick()));
						gmHandle.sendMessage(msg);
						break;
					case THANK_YOU:
						work=false;
						break;
					case GAME_STATE:
						if(msg.getGameOver() != null) {
							for(Player p : msg.getGameOver().getPlayers()) {
								if(p.getNick().equals(getNick())) {
									winner = p.getResult() == Result.WINNER ? 1 : 0;
									break;
								}
							}
						}
						break;
					case LOGOUT:
						break;
				}
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SocketException e) {
				//e.printStackTrace();
				Message m = new Message(MessageType.PLAYER_LEFT_GAME);
				GameId gid = new GameId(clientHandle.getGameId());
				m.setGameId(gid);
				communication.message.Player player = new Player(clientHandle.getNick());
				m.setPlayer(player);
				try {
					gmHandle.sendMessage(m);
					socket.close();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				Log.getInstance(ClientService.class).info("Connection Suddenly interuppted.");
				return;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
		
		}
	}
}
